from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import BasePermission

from models.models import Api


class APIPermission(BasePermission):
    method_map = {
        'get': 0,
        'post': 1,
        'delete': 2,
        'put': 3,
        'patch': 4
    }

    def has_permission(self, request, view):
        p = '{}.{}'.format(type(view).__name__, view.action)
        method = getattr(Api, request.method.upper())
        method = int(method)
        try:
            api = Api.objects.get(position=p, method=method)
        except Api.DoesNotExist:
            raise PermissionDenied(detail=f'{p}此接口未被记录')
        try:
            request.user.permission_group.api.get(id=api.id)
            return True
        except Api.DoesNotExist:
            raise PermissionDenied(detail=f'您没有{api.name}接口的权限, 请联系管理员')
